<template>
    <!-- 快速下单商品列表 
    @desc 快速下单商品列表
    @author kyle
    @date 2021-03-05
    @props
      productList  ———— 商品列表数据
    @method
      showSpec      ———— 显示规格弹窗
      updateCart    ———— 更新购物车
      goDetailPage  ———— 进入详情页
  -->
    <!-- 快速下单页面列表 -->
    <view class="quick-product-list">
        <view v-for="(item, index) in currentProductList" :key="index" class="product-list-item">
            <view class="product-info">

                <!-- <easy-pro-img customSize="128" :url="easyGetImgUrl(item.ThumbnailUrl160)"></easy-pro-img> -->
                <image class="image-wrapper" :src="easyGetImgUrl(item.ThumbnailUrl160)" mode="aspectFill" />

                <view class="product-info-main">
                    <view>
                        <!-- 商品名称 -->
                        <view class="product-info-title">
                            <text class="product-info-title-text">{{ item.ProductName }}</text>
                        </view>
                        <!-- {{item}} -->
                        <view v-if="item.ProductCode" class="desc-item"> 商品编码：{{ item.ProductCode }}</view>
                        <!-- 规格提示 -->
                        <view class="">
                            <text v-if="item.ProductSkuList.length === 1 && item.ProductSkuList[0].AttributeSkuDisplay"
                                class="desc-item">
                                规格：{{ item.ProductSkuList[0].AttributeSkuDisplay.replace("规格:", "") }}
                            </text>
                            <text v-if="item.ProductSkuList.length > 1" class="desc-item">
                                {{ item.ProductSkuList.length }}种规格可选
                            </text>
                        </view>

                        <!-- 备注 -->
                        <view v-if="displayData.IsShowRemark" class="desc-item">
                            备注：{{ item.ShortDescription ? item.ShortDescription : "" }}</view>
                        <!-- 换算率 -->
                        <!-- 			<view v-if="displayData.IsShowConversionRate" class="desc-item">
							换算：{{ item.ConversionRateText?item.ConversionRateText:'' }}</view> -->

                        <view class="price-box">
                            <view class="price-item">
                                <text class="price-text small">￥</text>
                                <text v-show="item.CurrentMinPrice < item.CurrentMaxPrice" class="price-text bold">{{
                                    item.CurrentMinPrice }}~</text>
                                <text class="price-text bold">{{ item.CurrentMaxPrice }}</text>
                            </view>
                            <text class="stock-text" v-if="
                                !displayData.NoCheckStock && getAppSet().IsProListShowSock && item.CurrentStock > 0
                            ">库存：{{ item.CurrentStock }}</text>
                            <text class="stock-text stock-text-main" @click="inquire(item)" v-else>查询库存</text>
                            <text class="stock-text"
                                v-if="!displayData.NoCheckStock && !getAppSet().IsProListShowSock">{{ item.CurrentStock
                                    <= 0 ? "无货" : "有货" }}</text>
                        </view>
                        <text class="price-text-original" v-if="item.RetailMinPrice < item.RetailMaxPrice">零售价:￥{{
                            item.RetailMaxPrice }}</text>
                        <text class="price-text-original" v-else>零售价:￥{{ item.RetailMinPrice }}</text>
                    </view>
                    <view class="action-box">
                        <view class="unit-item">
                            <view class="unit-btn" :class="{
                                'unit-change-able': item.ProductUnitList.length > 1,
                                active: productItemIndex === index,
                            }" @click="selectUnit(item, index)">
                                <text class="unit-text">{{ item.CurrentUnit }}</text>
                                <text class="arrow"
                                    :class="productItemIndex === index ? 'arrow-up' : 'arrow-down'"></text>
                            </view>
                            <view v-show="productItemIndex === index" class="custom-pop-over">
                                <view class="main">
                                    <text v-for="(element, i) in actions" :key="i" class="over-item"
                                        :class="item.CurrentUnit === element.unitName ? 'current' : ''"
                                        @click="onSelect(element, index, i)">
                                        {{ i > 0 ? "1" : "" }}{{ element.text }}
                                    </text>
                                </view>
                                <view class="bg" @tap="productItemIndex = -1"></view>
                            </view>
                        </view>
                        <!-- 右侧选规格/加减栏 -->
                        <view v-if="item.ProductSkuList && item.ProductSkuList.length > 1" class="product-specs">
                            <button class="btn btn-main btn-select-spec" @click.stop="showSpec(item, index)"
                                :disabled="item.CurrentStock <= 0 && !displayData.NoCheckStock"
                                :class="{ disable: item.CurrentStock <= 0 && !displayData.NoCheckStock }">
                                选规格
                            </button>
                        </view>
                        <view v-else-if="item.IsCustomized" class="product-specs">
                            <button class="btn btn-main btn-select-spec" @click.stop="showSpec(item, index)"
                                :disabled="item.CurrentStock <= 0 && !displayData.NoCheckStock"
                                :class="{ disable: item.CurrentStock <= 0 && !displayData.NoCheckStock }">
                                选规格
                            </button>
                        </view>
                        <view v-else class=" ">
                            <view v-for="(ite, inde) in item.CurrentUnitList" v-show="inde === item.UnitActiveIndex"
                                :key="inde">
                                <text v-show="false" v-if="tempType == 2">{{ getCurrentNum(ite, item) }}</text>
                                <template v-if="selectType == 4">
                                    <button class="btn btn-main btn-select-spec" @click="changeAmount(ite, item, 1)"
                                        style="font-size: 24rpx;">
                                        加入清单
                                    </button>
                                </template>
                                <view class="easy-num" v-else>
                                    <view class="input-number-box">
                                        <button class="btn btn-minus" :class="ite.Amount <= 0 ? 'disable' : ''"
                                            @click="changeAmount(ite, item, -1)">
                                            <text>-</text>
                                        </button>

                                        <view class="btn-input-box" @click="focusFn">
                                            <input v-model="ite.Amount" type="number" class="btn-input"
                                                @blur="changeAmount(ite, item, 0)" />
                                        </view>
                                        <button class="btn btn-plus"
                                            :disabled="ite.Amount >= ite.Stock && !displayData.NoCheckStock" :class="{
                                                disable: ite.Amount >= ite.Stock && !displayData.NoCheckStock,
                                                disable: item.CurrentStock <= 0 && !displayData.NoCheckStock,
                                            }" @click="changeAmount(ite, item, 1)">
                                            <text>+</text>
                                        </button>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapMutations, mapGetters, mapState } from "vuex"
import utilsOld from "@/utils/utilsOld.js"

import { upValetCartFn } from "@/utils/valetCartUtil.js"

import storage from "@/uni-sub-base/utils/storage.js"
import easyProImg from "@/components/easy/easy-pro-image.vue"
import easyNum from "@/components/easy/easy-num.vue"
export default {
    name: "ProductList",
    components: {
        easyProImg,
        easyNum,
    },
    props: {
        productList: {
            type: Array,
            required: true,
        },
        displayData: {
            type: Object,
            required: true,
        },
        tempType: {
            type: Number,
            default: 0,
        },
        isOnShow: {
            type: Boolean,
            default: true,
        },
        valetUserId: {
            type: Number,
            default: 0,
        },
        warehouseId: {
            type: Number,
            default: 0,
        },
        isGift: {
            type: String,
            default: "",
        },
        selectType: {
            type: [Number, String],
            default: 0,
        }
    },
    data() {
        return {
            productItemIndex: -1, // 商品选中序号
            productSpecIndex: -1, // 规格选中序号
            actions: [],
            minPrice: 0,
            maxPrice: 0,
            maxRetailPrice: 0,
            hasFreeProduct: false,
            isAble: true,
            isUpNum: true,
            setCartTimer: null,
            priceDecimalPlaces: 2,
            refresh: false,
        }
    },
    watch: {
        getValetCartData(e) {
            this.refresh = true
            this.$nextTick(() => {
                this.refresh = false
            })
            this.$forceUpdate()
        },
    },
    computed: {
        ...mapGetters(["getValetCartData"]),
        currentProductList() {
            const _list = JSON.parse(JSON.stringify(this.productList))
            if (_list && _list.length > 0) {
                _list.forEach((item) => {
                    if (item.ProductUnitList && item.ProductUnitList.length > 1) {
                        // 多规格增加比例换算值
                        item.ConversionRateText = ""
                        if (this.getAppSet().isCustomUnit) {
                            //不需要中间换算
                            let max = item.ProductUnitList[item.ProductUnitList.length - 1]
                            let min = item.ProductUnitList[0]
                            item.ConversionRateText = max.Ratio + min.UnitName + "/" + max.UnitName
                        } else {
                            const _li = item.ProductUnitList
                            for (let i = _li.length - 1; i > -1; i--) {
                                const _ratio =
                                    _li[_li.length - 1].Ratio % _li[i].Ratio === 0
                                        ? _li[_li.length - 1].Ratio / _li[i].Ratio
                                        : _li[_li.length - 1].Ratio + "/" + _li[i].Ratio
                                item.ConversionRateText += _ratio + _li[i].UnitName + (i > 0 ? "=" : "")
                            }
                        }
                    }
                    if (item.ProductSkuList && item.ProductSkuList.length === 1) {
                        // 单规格
                        item.CurrentUnitList = []
                        if (item.ProductUnitList && item.ProductUnitList.length > 0) {
                            for (let i = 0; i < item.ProductUnitList.length; i++) {
                                let _model = item.ProductUnitList[i].ProductSkuAttrList[0].SkuModel
                                if (_model) {
                                    let _obj = _model.ProductUnitPrice
                                    _obj.Stock = _model.Stock
                                    _obj.AddNum = _model.AddNum
                                    _obj.Title = item.ProductUnitList[i].Title
                                    item.CurrentUnitList.push(_obj)
                                } else if (item.ProductUnitList[i].ProductSkuAttrList[0].ProductAttrList[0]) {
                                    //美剧显示商品
                                    _model = item.ProductUnitList[i].ProductSkuAttrList[0].ProductAttrList[0].SkuModel
                                    if (_model) {
                                        let _obj = _model.ProductUnitPrice
                                        _obj.Stock = _model.Stock
                                        _obj.AddNum = _model.AddNum
                                        _obj.Title = item.ProductUnitList[i].Title
                                        item.CurrentUnitList.push(_obj)
                                    }
                                }
                            }
                        }
                    }
                })
            }
            console.log("_list==:", _list)
            return _list
        },
    },
    methods: {
        // 加减
        changeAmount(item, ite, type) {
            let num = Number(item.Amount)
            let stock = item.Stock
            let minNum = ite.MinNum
            let UnitRatio = item.Ratio
            let LimitBuy = ite.LimitBuy
            let addNum = Number(ite.AddNum)
            const _oldAmount = item.Amount

            if (this.displayData.NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type) * addNum
                    if (type == -1 && item.Amount * UnitRatio < minNum) {
                        item.Amount = 0
                    } else if (item.Amount * UnitRatio < minNum) {
                        minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                        let addN = minNum % addNum
                        let newNum = utilsOld.getMaxNum(minNum, addNum, addN)
                        item.Amount = newNum
                    }
                } else {
                    if (num > 0) {
                        let addN = num % addNum
                        let newNum = utilsOld.getMaxNum(num, addNum, addN)
                        item.Amount = newNum
                        if (item.Amount * UnitRatio < minNum) {
                            minNum = parseInt(minNum / UnitRatio) + (minNum % UnitRatio > 0 ? 1 : 0)
                            let addN = minNum % addNum
                            let newNum = utilsOld.getMaxNum(minNum, addNum, addN)
                            item.Amount = newNum
                        }
                    } else {
                        item.Amount = 0
                    }
                }
                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            this.refresh = true
            this.$nextTick(() => {
                this.refresh = false
            })
            this.$forceUpdate()

            this.isUpNum = false
            if (this.tempType == 2) {
                console.log(123123123)
                let param = {
                    amount: item.Amount,
                    productId: item.ProductId,
                    ratio: item.Ratio,
                    ratioUnit: item.UnitName,
                    skuId: item.SkuId,
                    valetUserId: this.valetUserId,
                    warehouseId: this.warehouseId,
                    isGift: this.isGift ? true : false,
                }
                console.log(param)
                upValetCartFn(param).then((res) => { })
            }
        },
        // 显示规格弹窗
        showSpec(item, index) {
            this.$emit("sku", item, index)
        },
        inquire(item) {
            this.$emit("inquire", item)
        },
        // 获取同一规格下最大值和最小值
        getPriceRange(arr) {
            if (arr && arr.length > 0) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].ProductAttrList && arr[i].ProductAttrList.length > 0) {
                        this.getPriceRange(arr[i].ProductAttrList)
                    } else {
                        if (arr[i].SkuModel && arr[i].SkuModel.ProductUnitPrice) {
                            if (arr[i].SkuModel.ProductUnitPrice.Price === 0) {
                                this.hasFreeProduct = true
                            }
                            this.minPrice =
                                this.minPrice < arr[i].SkuModel.ProductUnitPrice.Price && this.minPrice !== 0
                                    ? this.minPrice
                                    : arr[i].SkuModel.ProductUnitPrice.Price
                            this.maxPrice =
                                this.maxPrice > arr[i].SkuModel.ProductUnitPrice.Price
                                    ? this.maxPrice
                                    : arr[i].SkuModel.ProductUnitPrice.Price
                            this.maxRetailPrice =
                                this.maxRetailPrice > arr[i].SkuModel.ProductUnitPrice.RetailPrice
                                    ? this.maxRetailPrice
                                    : arr[i].SkuModel.ProductUnitPrice.RetailPrice
                        }
                    }
                }
            } else {
                console.log("arr不是数组，不能遍历")
            }
        },

        // 选单位
        onSelect(element, index, i) {
            this.currentProductList[index].UnitActiveIndex = i
            this.currentProductList[index].CurrentUnit = element.unitName
            this.currentProductList[index].CurrentUnitId = element.unitId
            this.minPrice = 0
            this.maxPrice = 0
            this.maxRetailPrice = 0
            this.hasFreeProduct = false
            this.getPriceRange(this.currentProductList[index].ProductUnitList[i].ProductSkuAttrList)
            if (this.maxPrice % 1 !== 0) {
                this.maxPrice = Number(this.maxPrice.toFixed(this.priceDecimalPlaces))
            }
            if (this.minPrice % 1 !== 0) {
                this.minPrice = Number(this.minPrice.toFixed(this.priceDecimalPlaces))
            }
            this.currentProductList[index].CurrentMinPrice = this.hasFreeProduct ? 0 : this.minPrice
            this.currentProductList[index].CurrentMaxPrice = this.maxPrice
            this.currentProductList[index].RetailMaxPrice = this.maxRetailPrice
            const _item = this.currentProductList[index]
            this.productItemIndex = -1
            this.$emit("changeUnit", _item)
        },
        // 显示单位选项
        selectUnit(item, index) {
            if (item.ProductUnitList.length < 1) {
                return
            }
            if (item.IsCustomized) {
                return
            }
            this.actions = []
            if (item.ProductUnitList && item.ProductUnitList.length > 1) {
                this.productItemIndex = this.productItemIndex === index ? -1 : index
                item.ProductUnitList.forEach((element) => {
                    this.actions.push({
                        text: element.Title,
                        ratio: element.Ratio,
                        unitName: element.UnitName,
                        unitId: element.UnitId,
                    })
                })
            }
        },
        onSelectSpec(element, index, inde, i) {
            this.currentProductList[index].ProductSkuList[inde].UnitActiveIndex = i
            this.currentProductList[index].ProductSkuList[inde].CurrentUnit = element.unitName
            this.currentProductList[index].ProductSkuList[inde].CurrentPrice = element.price
            this.productItemIndex = -1
            this.productSpecIndex = 1
            this.$forceUpdate()
        },
        selectUnitSpec(item, index, inde) {
            this.actions = []
            if (item.ProductUnitPriceList && item.ProductUnitPriceList.length > 1) {
                if (this.productItemIndex === index && this.productSpecIndex === inde) {
                    this.productItemIndex = -1
                    this.productSpecIndex = 1
                } else {
                    this.productItemIndex = index
                    this.productSpecIndex = inde
                }
                item.ProductUnitPriceList.forEach((element) => {
                    this.actions.push({
                        text: element.Title,
                        ratio: element.Ratio,
                        unitName: element.UnitName,
                        unitId: element.UnitId,
                        price: element.Price,
                    })
                })
            }
        },
        //关联购物车
        getCurrentNum(item, pro) {
            let value = 0
            //关联商品购物车
            if (this.getValetCartData) {
                this.getValetCartData.forEach((e) => {
                    if (e.ProductId == pro.ID) {
                        e.SubItems.forEach((sub) => {
                            if (item.UnitId == sub.UnitId && item.SkuId == sub.SkuId) {
                                value = sub.Amount
                            }
                        })
                    }
                })
            }

            item.Amount = value
            return value
        },
        reSetAttr(e) {
            return utilsOld.reSetAttr(e)
        },
        focusFn() { },
    },
}
</script>

<style lang="scss" scoped>
.quick-product-list {
    position: relative;
}

.product-list-item {
    display: flex;
    flex-direction: column;
    background: $color-white;
    padding: $app-page-padding;
    margin-bottom: 10rpx;
    border-top-left-radius: 8rpx;
    border-bottom-left-radius: 8rpx;

    .product-info {
        display: flex;
        flex: 1;
        flex-direction: row;

        .product-info-main {
            display: flex;
            flex: 1;
            flex-direction: column;
        }

        .product-info-title {
            display: flex;
            flex-direction: row;
            margin-bottom: 2rpx;

            .product-info-title-text {
                display: flex;
                flex: 1;
                color: $color-black;
                font-size: $font-size-28;
                font-weight: 700;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 36rpx;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                word-break: break-all;
            }

            .icon-favorite {
                padding-left: 20rpx;
            }
        }
    }

    .product-info-middle {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-bottom: 20rpx;

        .space-text {
            display: flex;
            flex: 1;
        }
    }

    .product-info-bottom {
        display: flex;
        flex-direction: row;
        align-items: center;

        .left {
            display: flex;
            flex-direction: row;
            flex: 1;

            .product-price {
                display: flex;
                align-items: center;
                margin-right: 10rpx;

                .price-text {
                    color: $color-orange-1;
                    font-size: $font-size-28;
                    font-weight: 700;
                    margin-right: 10rpx;
                }

                .unit-text {
                    color: $app-color-text-tip;
                    font-size: $font-size-20;
                }
            }
        }

        .right {
            .product-specs {
                width: 140rpx;

                .btn {
                    height: 50rpx;
                    font-size: 24rpx !important;
                }
            }
        }
    }
}

.product-specs {
    .btn {
        font-size: 24rpx !important;
    }
}

.desc-item {
    margin-bottom: 4rpx;
    color: $app-color-text-tip;
    font-size: $font-size-24;

    &:last-child {
        margin-bottom: 0;
    }

    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
}

.price-box {
    display: flex;
    flex-direction: row;
    align-items: center;

    .price-item {
        display: flex;
        flex: 1;
        align-items: flex-end;

        .price-text {
            font-size: $font-size-32;
        }

        .small {
            font-size: $font-size-26;
            margin-bottom: 3rpx;
        }
    }
}

.action-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 20rpx;

    .unit-item {
        display: flex;
        flex: 1;
        position: relative;
    }
}

.stock-text {
    font-size: $font-size-22;
    color: $app-color-text-tip;
    margin-left: 6rpx;
}

.stock-text-main {
    color: $app-color-main;
}

.sku-list-item {}

.unit-btn {
    min-width: 80rpx;
    max-width: 100rpx;
    height: 42rpx;
    border-radius: 70rpx;
    border: solid 1rpx $color-gray-3;
    display: flex;
    align-items: center;
    justify-content: center;

    .unit-text {
        margin-right: 10rpx;
    }

    .arrow {
        border: solid black;
        border-width: 0 1px 1px 0;
        padding: 2px;
    }

    .arrow-up {
        margin-top: 8rpx;
    }

    .arrow-down {
        margin-bottom: 5rpx;
    }
}

.unit-change-able {
    border: solid 1rpx $app-color-main;

    .arrow {
        border-color: $app-color-main;
    }
}

.active {
    border-color: $app-color-main;

    .arrow {
        border-color: $app-color-main;
    }
}

.custom-pop-over {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 9;
    top: 60rpx;

    .main {
        position: relative;
        z-index: 1;
        background: $color-white;
        border-radius: 8rpx;
        box-shadow: 0 0 40rpx #ccc;
        max-width: 160rpx;

        .over-item {
            height: 60rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            border-bottom: solid 1rpx #f4f4f4;

            &:first-child {
                border-radius: 8rpx 8rpx 0rpx 0rpx;
            }

            &:last-child {
                border-radius: 0rpx 0rpx 8rpx 8rpx;
                border-bottom: 0;
            }
        }

        .current {
            background: $app-color-main;
            color: $color-white;
        }
    }

    .bg {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 0;
    }
}

.btn-plus {
    width: 48rpx;
    height: 48rpx;
    line-height: 48rpx;
    border-radius: $border-radius-10;
    background: $app-color-main;

    text {
        justify-content: center;
        align-items: center;
        position: relative;
        font-size: 38rpx;
        color: $color-white;
        display: flex;
        align-self: center;
        margin-bottom: 2rpx;
    }
}

.btn-minus {
    width: 48rpx;
    height: 48rpx;
    line-height: 48rpx;
    border-radius: $border-radius-10;
    border: solid 1rpx $app-color-main;

    &:before {
        background-color: $color-white;
    }

    text {
        justify-content: center;
        align-items: center;
        position: relative;
        font-size: 38rpx;
        color: $app-color-main;
        display: flex;
        align-self: center;
        margin-bottom: 2rpx;
    }
}

.btn-input-box {
    height: 44rpx;

    &:before {
        background: $transparent;
    }

    .btn-input {}
}

.disable {
    text {
        color: $color-gray-3;
    }
}

.bold {
    font-weight: 700;
}

.btn-select-spec {
    height: 52rpx;
    border-radius: 100rpx;
    font-size: $font-size-30;
}

.input-number-box {
    border-radius: 100rpx;
    padding: 4rpx 6rpx;
    border: solid 1rpx #eaeaea;

    .btn {
        width: 52rpx;
        height: 52rpx;
        border-radius: 100rpx;
        background: #f2f2f2;
        border: none;
        padding: 0;

        text {
            color: $color-black;
            font-size: 40rpx;
        }
    }

    .btn-plus {
        background: $app-color-main;

        text {
            color: $color-white;
        }
    }

    .disable {
        border: none;

        text {
            color: #cccccc;
        }
    }

    .btn-input {
        position: relative;
        z-index: 1;
        height: 56rpx;
        width: 80rpx;
        line-height: 1;
        border: none;
        background: transparent;
        text-align: center;
        font-size: $font-size-28;
        outline: none;
    }
}

.price-text-original {
    color: #ccc;
}

.image-wrapper {
    width: 120rpx;
    height: 120rpx;
    margin-right: $app-page-padding;
    border-radius: 8rpx;
}
</style>
